#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>

#define HOST "localhost"
#define USERNAME "root"
#define PASSWORD ""
#define DATABASE "tcmu"

void printResult(MYSQL *mysqlPrint);

int main()
{
    MYSQL connection;
    mysql_init(&connection);
    mysql_real_connect(&connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, 0);

    // Test the connection with mysql host
    if (mysql_ping(&connection))
	{
		printf("Mysql connction is broken.\n");
        return 0;
    }
    mysql_query(&connection, "set names 'utf8'");
    char *sql = "select key,value from kv";
    int sql_execute_result = mysql_query(&connection, sql);
    if (sql_execute_result)
	{
        // If query failed, get the error response code and execute error handler logic.
		int error_code = mysql_errno(&connection);
		printf("Query failed! Error Code : %d. Error Info : %s.\n", error_code, mysql_error(&connection));
		printf("Start to reconnect the MYSQL.\n");

        // As for 2013 and 2006, you can retry to connect the mysql.
		if((error_code == 2013 || error_code == 2006) && !mysql_real_connect(&connection,HOST,USERNAME,PASSWORD,DATABASE,0,NULL,0))
		{
        	printf("Error reconnecting: \n");
        	printf("%s\n",mysql_error(&connection));
			return 0;
	    }
		else
		{
			printf("Reconnect successfully!\n");
			sql_execute_result = mysql_query(&connection, sql);
		}
	}
    printResult(&connection);
    mysql_close(&connection);
    return 0;
}

void printResult(MYSQL *mysqlPrint)
{
    MYSQL_RES * result;
    int numFields = 0;
    int numRows = 0;
    MYSQL_FIELD * field;
    MYSQL_ROW row;
    int i = 0;
    result = mysql_store_result(mysqlPrint);
    numFields = mysql_num_fields(result);
    numRows = mysql_num_rows(result);
    while(field = mysql_fetch_field(result))
        printf("%s\t", field->name);
    printf("\n");
    if(result)
    {
        while(row = mysql_fetch_row(result))
        {
            for(i = 0; i < numFields; i++)
            {
                printf("%s\t", row[i]);
            }
            printf("\n");
        }
    }
    mysql_free_result(result);
}
